package com.acme.bankapp.server;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;

import com.acme.bankapp.server.command.Command;
import com.acme.bankapp.server.command.CommandFactory;
import com.acme.bankapp.server.command.ExitCommand;

public class RequestHandler implements Runnable {

	Socket connectionSocket;
	ObjectOutputStream out;
	ObjectInputStream in;
	String remoteHost;
	
	CommandFactory commandFactory;

	public RequestHandler(Socket socket, CommandFactory factory) throws IOException {
		commandFactory = factory;
		connectionSocket = socket;
		remoteHost = connectionSocket.getInetAddress().getHostName();
		log("connection received");

		out = new ObjectOutputStream(connectionSocket.getOutputStream());
		in = new ObjectInputStream(connectionSocket.getInputStream());
		log("connection successful");
	}

	@Override
	public void run() {
		String message;
		String response;
		Command command;

		try {
			do {
				message = (String) in.readObject();
				log(message);

				command = commandFactory.createCommand(message);
				
				response = command.execute();
				out.writeObject(response);
				out.flush();
			} while (!(command instanceof ExitCommand));

		} catch (ClassNotFoundException e) {
			log("received message in unknown format");
		} catch (IOException e) {
			e.printStackTrace();
		} finally {

			log("terminating");
			try {
				in.close();
				out.close();
				connectionSocket.close();
			} catch (IOException e) {
				e.printStackTrace();
			}

		}

	}

	private void log(String str) {
		System.out.printf("[%s %s] %s%n",
				remoteHost,
				Thread.currentThread().getName(),
				str);
	}

}
